var parma = process.argv.splice(2);
var http = require("http");
var fs = require("fs");
var path = require("path");
var url = require('url');
var port = parma[0] || 80;
var proxyIp = parma[1];
var httpProxy = require("http-proxy");
let util = require("util");

/**
 * SSR 服务端渲染
 */
const {
    createBundleRenderer
} = require('vue-server-renderer');
// 生成服务端渲染函数
const renderer = createBundleRenderer(require('./dist/vue-ssr-server-bundle.json'), {
    // 推荐
    runInNewContext: false,
    // 模板html文件
    template: fs.readFileSync(path.join(__dirname, "./dist/index.html"), 'utf-8'),
    // client manifest
    clientManifest: require('./dist/vue-ssr-client-manifest.json')
})

function renderToString(context) {
    return new Promise((resolve, reject) => {
        renderer.renderToString(context, (err, html) => {
            err ? reject(err) : resolve(html)
        })
    })
}

/**
 * 获取IP地址
 */
var os = require('os');
let ipAddress = {
    IPv4: {
        address: "localhost"
    }
};
let {
    WLAN
} = os.networkInterfaces();

if (WLAN) {
    WLAN.map(item => {
        ipAddress[item.family] = item;
    });
}
/**
 * 访问请点击
 */
console.log(`Please click on the access： http://${ipAddress.IPv4.address}:${port}/`);

/**
 * HTTP-PROXY代理
 */
var proxy = httpProxy.createProxyServer({
    target: "http://" + proxyIp
});

proxy.on("error", function (err, req, res) {
    res.writeHead(500, {
        "content-type": "text/plain"
    });
    res.end('Something went wrong. And we are reporting a custom error message.');
});

/**
 * SEO字典表
 */
const seoDictionaries = require("./seoDictionaries.js");

/**
 * GET query 参数解析
 * @param {} query 
 */
const setQueryParam = function (query) {
    if (util.isNull(query)) {
        return {};
    };
    let queryArr = query.split("&");
    let param = {};
    for (let i = 0; i < queryArr.length; i++) {
        let queryItem = queryArr[i].split("=");
        let key = queryItem[0];
        let keyId = queryItem[1];
        let content = null;
        if (util.isNullOrUndefined(seoDictionaries[key])) {
            /**
             * 当KEY为空时 || 跳转该次循环，继续下一个
             */
            continue;
        }
        if (/^[0-9a-zA-Z]{1,}(,[0-9a-zA-Z]{1,}){1,}$/.test(keyId)) {
            /**
             * 检测是否有“,”号，判断为多项关键词
             * 匹配关键词字典表
             */
            content = keyId.split(",").map(id => seoDictionaries[key][id]);
        } else {
            /**
             * 查询内容为单一组件时
             * 匹配关键词字典表
             */
            content = seoDictionaries[key][keyId];
        }
        param[key] = content;
        content = null;
        key = null;
        keyId = null;
    }
    return param;
};
/**
 * HTTP服务
 */
http.createServer(function (Request, Response) {
    var link = url.parse(Request.url).pathname;
    if (/^(\/[0-9a-zA-Z]{0,}){1,}$/.test(link)) {
        /**
         * 判断 接口 || 路由
         */
        let context = {
            url: link,
            /**
             * 标题
             */
            title: seoDictionaries.title[link],
            /**
             * 关键词
             */
            keywords: "",
            /**
             * 长尾词
             */
            description: "",
        };
        /**
         * 获取query参数
         */
        let query = url.parse(Request.url).query;
        /**
         * 判断是否为参数 多项选必须用“,”【半角】号隔开，
         */
        let isQuery = /^([0-9a-zA-Z]{1,}=[0-9a-zA-Z,]{1,})(&[0-9a-zA-Z]{1,}=[0-9a-zA-Z,]{1,}){0,}$/.test(query)
        if (isQuery) {
            /**
             *  query为该参数类型时；
             */
            let queryParam = setQueryParam(query);
            let queryObj = {
                price: queryParam.price || "",
                station: queryParam.station ? " " + queryParam.station : "",
                metro: queryParam.metro ? " " + queryParam.metro : "",
                plate: queryParam.plate ? " " + queryParam.plate : "",
                area: queryParam.area ? " " + queryParam.area : "",
                country: queryParam.country ? " " + queryParam.country : "",
                city: queryParam.city || "",
            };
            context.param = queryObj;
            /**
             * 标题：价格、站点、地铁线、板块、区域、国家、城市、路径标题；
             */
            context.title = `${queryObj.price}${queryObj.station}${queryObj.metro}${queryObj.plate}${queryObj.area}${queryObj.country}${queryObj.city}${seoDictionaries.title[link]}`;
            /**
             * 关键词：价格、站点、地铁线、板块、区域、国家、城市、路径标题；
             */
            context.keywords = `${queryObj.price}${queryObj.station}${queryObj.metro}${queryObj.plate}${queryObj.area}${queryObj.country}${queryObj.city}${seoDictionaries.title[link]}`;
            /**
             * 长尾词：价格、站点、地铁线、板块、区域、国家、城市、路径标题；
             */
            context.description = `${queryObj.price}${queryObj.station}${queryObj.metro}${queryObj.plate}${queryObj.area}${queryObj.country}${queryObj.city}${seoDictionaries.title[link]}`;
        }
        /**
         * VUE-SERVER-SSR 渲染
         */
        renderToString(context).then(html => {
            let data = html;
            Response.writeHead(200, {
                'Content-type': "text/html;charset=utf-8;"
            });
            Response.write(data);
            Response.end();
        }).catch(err => {
            Response.writeHead(err.code, {
                'Content-type': "text/html;charset=utf-8;"
            });
            Response.write("失败");
            Response.end();
        });
        return;
    }
    /**
     * 请求路径为文件时
     */
    var pathName = path.join(__dirname, "/dist" + link);
    fs.readFile(pathName, function (err, stdout) {
        if (!err) {
            var data = stdout;
            // 设置文件类型
            switch (path.extname(pathName)) {
                case ".html":
                    Response.writeHead(200, {
                        "Content-Type": "text/html;charset=utf-8;"
                    });
                    break;
                case ".js":
                    Response.writeHead(200, {
                        "Content-Type": "text/javascript"
                    });
                    break;
                case ".css":
                    Response.writeHead(200, {
                        "Content-Type": "text/css"
                    });
                    break;
                case ".json":
                    Response.writeHead(200, {
                        "Content-Type": "text/json"
                    });
                    break;
                case ".gif":
                    Response.writeHead(200, {
                        "Content-Type": "image/gif"
                    });
                    break;
                case ".jpg":
                    Response.writeHead(200, {
                        "Content-Type": "image/jpeg"
                    });
                    break;
                case ".png":
                    Response.writeHead(200, {
                        "Content-Type": "image/png"
                    });
                    break;
                default:
                    Response.writeHead(200, {
                        "Content-Type": "application/octet-stream"
                    });
            };
            Response.write(data);
            Response.end();
        } else {
            Response.writeHead(200, {
                'Content-type': "text/html;charset=utf-8;"
            });
            Response.write(`<a>${pathName}不存在</a>`);
            Response.end();
        }
    });
}).listen(port);